package com.iflytek.jzcpx.procuracy.web.ocr.controller;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iflytek.jzcpx.procuracy.common.enums.CommonResultEnum;
import com.iflytek.jzcpx.procuracy.common.enums.MetricEnum;
import com.iflytek.jzcpx.procuracy.common.exception.InvalidParameterException;
import com.iflytek.jzcpx.procuracy.common.exception.ViewException;
import com.iflytek.jzcpx.procuracy.common.result.Result;
import com.iflytek.jzcpx.procuracy.common.result.WebResult;
import com.iflytek.jzcpx.procuracy.common.util.Logs;
import com.iflytek.jzcpx.procuracy.common.util.MetricUtil;
import com.iflytek.jzcpx.procuracy.ocr.entity.swx.BatchOcrVO;
import com.iflytek.jzcpx.procuracy.ocr.entity.swx.OcrTxsbVo;
import com.iflytek.jzcpx.procuracy.ocr.entity.swx.OcrWJsbMultiResult;
import com.iflytek.jzcpx.procuracy.ocr.entity.swx.OcrWJsbSingleResult;
import com.iflytek.jzcpx.procuracy.ocr.entity.swx.WjOcrsbjgRes;
import com.iflytek.jzcpx.procuracy.ocr.entity.swx.result.Wjsbjg;
import com.iflytek.jzcpx.procuracy.ocr.entity.txsb.JzRecognizeResult;
import com.iflytek.jzcpx.procuracy.ocr.entity.txsb.JzRecognizeVo;
import com.iflytek.jzcpx.procuracy.ocr.entity.txsb.PicFileRecognizeReqVo;
import com.iflytek.jzcpx.procuracy.ocr.recognize.model.BDAJQueryDto;
import com.iflytek.jzcpx.procuracy.ocr.recognize.model.OcrResultPdfQueryDto;
import com.iflytek.jzcpx.procuracy.ocr.recognize.model.OcrResultQueryDto;
import com.iflytek.jzcpx.procuracy.ocr.recognize.model.OcrResultRequestVo;
import com.iflytek.jzcpx.procuracy.ocr.recognize.model.Wjtz;
import com.iflytek.jzcpx.procuracy.ocr.service.OcrService;
import com.iflytek.jzcpx.procuracy.web.config.MetricInterface;
import com.iflytek.jzcpx.procuracy.web.ocr.bd.OcrBDService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/iflytek/api", produces = "application/json")
@Api(value = "批量文件转双层pdf能力接口-赛维讯定制版", tags = "OCR(包括图像识别)")
public class OcrController {

    private static final Logger logger = LoggerFactory.getLogger(OcrController.class);

    @Autowired
    private OcrBDService ocrBDService;

    @Autowired
    private OcrService ocrService;

    /**
     * 批量文件转双层pdf异步接口 ocr识别
     *
     * @param batchOcrVO
     *
     * @return
     */
    @ApiOperation(value = "批量文件转双层pdf接口", notes = "MQ消息")
    @PostMapping("/batch/file2DoublePdf")
    public WebResult<?> batchFile2DoublePdf(@RequestBody BatchOcrVO batchOcrVO, HttpServletRequest request)
            throws Exception {
        logger.info("批量文件转双层pdf接口, batchOcrVO: {}", batchOcrVO);
        JSONObject obj = MetricUtil.buildMetricParam(request, MetricEnum.OCR, request.getRequestURI());
        obj.put("systemid", batchOcrVO.getSystemid());
        obj.put("bsbh", batchOcrVO.getBsbh());
        obj.put("dwbm", batchOcrVO.getDwbm());
        obj.put("taskid", batchOcrVO.getTaskid());
        obj.put("remark", "批量文件转双层pdf接口:MQ消息");
        Result<String> result = ocrBDService.batchOcrToPdf(batchOcrVO, obj);
        logger.info("批量文件转双层pdf接口结束, batchOcrVO: {}", batchOcrVO);
        return null;
    }

    /**
     * 获取卷宗OCR识别结果 api-07
     *
     * @param param
     */
    @PostMapping("/GetJZOCRSBJG")
    @ApiOperation(value = "获取卷宗OCR识别结果")
    public OcrWJsbMultiResult getOcrResult(@RequestBody OcrResultQueryDto param) {
        logger.info("获取卷宗OCR识别结果入参 {}:",JSON.toJSONString(param));
        return ocrService.findOcrResult(param.getBmsah(), param);
    }

    /**
     * 赛维讯2.0统一接口-ocr服务
     * 将传入需要识别的图片或文件进行OCR识别并返回识别结果  1.2.10
     *
     * @param ocrParamVO
     * @return
     */
    @ApiOperation(value = "单个文件合成双层pdf")
    @PostMapping("/ocr/wjsb")
    @MetricInterface(stringVal = "单个文件合成双层pdf")
    public OcrWJsbSingleResult ocrWjsb(@Validated @RequestBody OcrResultPdfQueryDto ocrParamVO,HttpServletRequest request) throws Exception {
    	//JSONObject obj=MetricUtil.buildMetricParam(request, MetricEnum.OCR, request.getRequestURI());
        logger.info("单个文件合成双层pdf, ocrParamVO: {}", ocrParamVO);
    	Result<OcrWJsbSingleResult> result = ocrBDService.ocrToPdf(ocrParamVO);
        return result.getData();
    }

    /**
     * 批量文件图像识别接口，订阅中台消息，当中台发出TXSB_SBQQ时
     * DZJZ_SBWC(电子卷宗识别完成)
     *
     * @param batchOcrVO
     *
     * @return
     */
    @ApiOperation(value = "批量文件图像识别接口", notes = "MQ消息")
    @PostMapping("/batch/batchFileTxsb")
    public WebResult<?> batchFileTxsb(@RequestBody BatchOcrVO batchOcrVO, HttpServletRequest request) throws Exception {
        logger.info("批量文件图像识别开始, batchOcrVO: {}", batchOcrVO);
        JSONObject obj = MetricUtil.buildMetricParam(request, MetricEnum.OCR, request.getRequestURI());
        obj.put("systemid", batchOcrVO.getSystemid());
        obj.put("bsbh", batchOcrVO.getBsbh());
        obj.put("dwbm", batchOcrVO.getDwbm());
        obj.put("taskid", batchOcrVO.getTaskid());
        obj.put("remark", "批量文件图像识别接口:MQ消息");
        Result<String> result = ocrBDService.batchRecognize(batchOcrVO, obj);
        logger.info("批量文件图像识别结束, batchOcrVO: {}", batchOcrVO);
        return null;

    }

    //新增获取图像识别的接口

    /**
     * 赛维讯2.0统一接口-ocr服务
     *
     * @param recognizeVO
     * @return
     */
    @ApiOperation(value = "单个图片证据识别")
    @PostMapping("/txsb/ConductTxsb")
    @MetricInterface(stringVal = "单个图片证据识别")
    public WebResult<List<Wjtz>> ocrTxsb(@RequestBody OcrTxsbVo recognizeVO,HttpServletRequest request) throws Exception {
    	//JSONObject obj=MetricUtil.buildMetricParam(request, MetricEnum.OCR, request.getRequestURI());
        logger.info("单个图片证据识别, recognizeVO: {}", recognizeVO);
        Result<List<Wjtz>> recognizeResult = ocrBDService.recognize(recognizeVO);

        return new WebResult<>(recognizeResult);
    }
    
    
    /**
     * 赛维讯2.0统一接口-ocr服务  获取卷宗图像识别结果api-06
     *
     * @param JzRecognizeVo
     * @return
     */
    @ApiOperation(value = "获取卷宗图像识别结果（api-06）")
    @PostMapping("/txsb/GetJZTXSBJG")
    public WebResult<JzRecognizeResult> getJZTXSBJG(@RequestBody JzRecognizeVo jzRecognizeVo) throws Exception {
        logger.info("获取卷宗图像识别结果, jzRecognizeVo: {}", jzRecognizeVo);
    	WebResult<JzRecognizeResult> recognizeResult= ocrService.recognize(jzRecognizeVo.getBmsah());
    	recognizeResult.setCode(200);
    	recognizeResult.setSuccess(true);
    	return recognizeResult;
    }

    /**
     * 赛维讯2.0统一接口-ocr服务  获取文件图像识别结果（api-07）
     *
     * @param JzRecognizeVo
     *
     * @return
     */
    @ApiOperation(value = "获取文件图像识别结果（api-07）")
    @PostMapping("/txsb/GetWJTXSBJG")
    @MetricInterface(stringVal = "获取文件图像识别结果（api-07）")
    public WebResult<?> getWJTXSBJG(@RequestBody PicFileRecognizeReqVo picFileRecognizeReqVo,
            HttpServletRequest request) throws Exception {
        logger.info("获取文件图像识别结果, picFileRecognizeReqVo: {}", picFileRecognizeReqVo);
        //JSONObject obj=MetricUtil.buildMetricParam(request, MetricEnum.OCR, request.getRequestURI());
        WebResult<?> picFileRecognizeResult = ocrBDService.recognize(picFileRecognizeReqVo);
        picFileRecognizeResult.setCode(picFileRecognizeResult.getCode());
        picFileRecognizeResult.setSuccess(picFileRecognizeResult.isSuccess());
        return picFileRecognizeResult;
    }

    /**
     * 绑定部门受案号
     *
     * @param param
     */
    @PostMapping("/BDAJ")
    @ApiOperation(value = "绑定部门受案号")
    public void bindBMSAH(@RequestBody BDAJQueryDto param) {
	logger.info("绑定部门受案号开始，请求 参数param:{}",JSON.toJSONString(param));
        ocrService.relationShipTaskAndBMSAH(param.getBmsah(), param.getBsbhlist(), param.getDwbm(),param.getJzbh());
    }

    /**
     * 解绑部门受案号
     *
     * @param param
     */
    @PostMapping("/unbind/BDAJ")
    @ApiOperation(value = "解绑部门受案号")
    public void unBindBMSAH(@RequestBody BDAJQueryDto param) {
        logger.info("解绑部门受案号, param: {}", param);
        ocrService.unRelationShipTaskAndBMSAH(param.getBmsah(), param.getBsbhlist(), param.getDwbm(),param.getJzbh());
    }

    /**
     * 将传入需要识别的图片或文件进行OCR识别并返回识别结果
     */
    @PutMapping("/GetWJOCRSBJG")
    @Deprecated
    public WjOcrsbjgRes GetWJOCRSBJG(@RequestBody OcrResultRequestVo params, HttpServletRequest request) {
        logger.info("获取文件OCR识别结果, params: {}", params);
        params.setNofile(false);//先不处理mq消息的情况
        //校验授权的系统标志，校验过了才可以调用系统的ocr识别功能
        String systemid = request.getHeader("systemid");
        String token = request.getHeader("token");
        WjOcrsbjgRes res = null;
        try {
            res = ocrService.fileRecognize(params);
        }
        catch (Exception ex) {
            //
            logger.error("", ex);
        }
        finally {
            //res=null;
        }
        res.setCode("1");
        res.setMessage("Success");
        res.setSuccess(true);
        return res;
    }

    /**
     * 获取文件OCR识别结果（api-08）
     */
    @PostMapping("/GetWJOCRSBJG")
    @MetricInterface(stringVal = "获取文件OCR识别结果（api-08）")
    public WebResult<Wjsbjg> getWJOCRSBJG(@RequestBody OcrResultRequestVo ocrParam, HttpServletRequest request) {
        logger.info("获取文件OCR识别结果, ocrParam: {}", Logs.chop(ocrParam));
        String wjbh = ocrParam.getWjbh();
        // logger.debug("获取文件OCR识别结果,   {}", JSONUtil.toStrDefault(ocrParam));
        try {
        	/*String filePath="C:\\Users\\Administrator.DGYU.000\\Desktop\\证据卷\\证据卷\\证据材料卷_页面_06.jpg";
        	byte[] b = Files.readAllBytes(Paths.get(filePath));
			String s = org.apache.commons.codec.binary.Base64.encodeBase64String(b);
			
			logger.info("base64: {}", s);*/
            //JSONObject obj=MetricUtil.buildMetricParam(request, MetricEnum.OCR, request.getRequestURI());

            Wjsbjg wjsbjg = ocrService.recognize(ocrParam);
            logger.info("获取文件OCR识别结果完成, wjbh: {}", wjbh);

            WebResult<Wjsbjg> result = WebResult.success(wjsbjg);
            result.setCode(200);
            result.setSuccess(true);
            return result;
        }
        catch (Exception e) {
            logger.warn("获取文件OCR识别结果异常, wjbh: {}", wjbh, e);
            return buildExceptionResult(e);
        }
    }

    private WebResult<Wjsbjg> buildExceptionResult(Exception e) {
        if (e instanceof InvalidParameterException) {
            return new WebResult<>(((InvalidParameterException) e).getResultType());
        }
        else if (e instanceof ViewException) {
            return new WebResult<>(((ViewException) e).getResultType());
        }

        WebResult<Wjsbjg> result = new WebResult<>();
        result.update(CommonResultEnum.FAILED, e.getMessage());
        return result;
    }
}
